﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mail;
using System.Xml;
using System.Xml.Xsl;
using BONSAI.Common.Enum;

namespace BONSAI.Common
{
    /// <summary>
    /// (C)2009 EBizWorld. All rights reserved.
    /// @author VietTQ
    /// @creationDate 12-Jul-2009
    /// </summary>
    public class EmailPacket
    {
        #region Properties
        private string strFrom = string.Empty;
        private string strTo = string.Empty;
        private string strBcc = string.Empty;
        private string strCc = string.Empty;
        private string strAttachmentPath = string.Empty;
        private string strEmailTemplate = string.Empty;

        public string From
        {
            get { return strFrom; }
            set { strFrom = value; }
        }

        public string To
        {
            get { return strTo; }
            set { strTo = value; }
        }

        public string Bcc
        {
            get { return strBcc; }
            set { strBcc = value; }
        }

        public string Cc
        {
            get { return strCc; }
            set { strCc = value; }
        }

        public string AttachmentPath
        {
            get { return strAttachmentPath; }
            set { strAttachmentPath = value; }
        }

        public string EmailTemplate
        {
            get { return strEmailTemplate; }
            set { strEmailTemplate = value; }
        }
        #endregion

        public void SendEmail(IDictionary objDictionary, SendMailTypeEnum sendMailEnum)
        {
            var objXslt = new XslTransform();
            objXslt.Load(strEmailTemplate);
            var xmlDoc = new XmlDocument();
            xmlDoc.AppendChild(xmlDoc.CreateElement("EmailMessage"));
            var xpathNav = xmlDoc.CreateNavigator();

            var xslArg = new XsltArgumentList();
            if (objDictionary != null)
            {
                foreach (DictionaryEntry entry in objDictionary)
                {
                    xslArg.AddParam(entry.Key.ToString(), "", entry.Value);
                }
            }

            var emailBuilder = new StringBuilder();
            var xmlWriter = new XmlTextWriter(new StringWriter(emailBuilder));

            objXslt.Transform(xpathNav, xslArg, xmlWriter, null);

            var emailDoc = new XmlDocument();
            emailDoc.LoadXml(emailBuilder.ToString());
            var titleNode = emailDoc.SelectSingleNode("//title");
            var subjectText = titleNode.InnerText;
            var bodyNode = emailDoc.SelectSingleNode("//body");
            var bodyText = bodyNode.InnerXml;

            if (SendMailTypeEnum.SEND_AUTO_EMAIL.Equals(sendMailEnum))
            {
                bodyText = HttpUtility.HtmlDecode(bodyText);
            }

            if (SendMailTypeEnum.SEND_CONTACTUS_EMAIL.Equals(sendMailEnum))
            {
                bodyText = BONSAIUtils.EncodeNewLineForward(bodyText);
            }
            if (SendMailTypeEnum.SEND_ORDER_EMAIL.Equals(sendMailEnum))
            {
                bodyText = HttpUtility.HtmlDecode(BONSAIUtils.DecodeForSendOrderMail(bodyText));
            }
            if (SendMailTypeEnum.SEND_FORUMCOMMENT_EMAIL.Equals(sendMailEnum))
            {
                bodyText = BONSAIUtils.EncodeNewLineForward(bodyText);
            }




            SendEmail(subjectText, bodyText, sendMailEnum);
        }

        private void SendEmail(string subjectText, string bodyText, SendMailTypeEnum sendMailEnum)
        {
            var mailMessage = new System.Web.Mail.MailMessage { From = Convert.ToString(ConfigurationSettings.AppSettings["SystemEmail"]) };

            //start config google

            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = ("smtp.gmail.com");

            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = "465";

            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";


            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;

            // Edit username & password

            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = Convert.ToString(ConfigurationSettings.AppSettings["SystemEmail"]);

            mailMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = Convert.ToString(ConfigurationSettings.AppSettings["SystemMailPassword"]);
            //end google

            mailMessage.To = strTo;
            mailMessage.Subject = subjectText;
            mailMessage.Body = bodyText;
            mailMessage.BodyFormat = MailFormat.Html;

            //decode
            mailMessage.BodyEncoding = Encoding.UTF8;
            //end

            try
            {
                //.client.Send(mailMessage);

                SmtpMail.Send(mailMessage);
            }
            catch (SmtpException e)
            {
                //Logger.Write("Error send mail: " + e);
            }
        }

        private static IList<MailAddress> GetEmailAddress(string mail)
        {
            var listMailAddress = new List<MailAddress>();

            if (string.IsNullOrEmpty(mail))
                return null;

            if (BONSAIUtils.IsValidEmail(mail))
            {
                listMailAddress.Add(new MailAddress(mail));
                return listMailAddress;
            }

            if (mail.IndexOf(";") > 0 || mail.IndexOf(",") > 0)
            {
                var mailAddrs = mail.Split(new[] { ';', ',' });
                foreach (var toAddr in mailAddrs)
                {
                    if (BONSAIUtils.IsValidEmail(toAddr))
                    {
                        listMailAddress.Add(new MailAddress(toAddr));
                    }
                }
            }
            else
            {
                if (BONSAIUtils.IsValidEmail(mail))
                {
                    listMailAddress.Add(new MailAddress(mail));
                    return listMailAddress;
                }
                return null;
            }

            return listMailAddress;
        }

        private MailAddress GetEmailFrom()
        {
            if (!strFrom.Equals(string.Empty))
            {
                return new MailAddress(strFrom);
            }
            var emailFrom = GetSystemEmail();
            var displayEmailFrom = GetSystemDisplayName();

            return new MailAddress(emailFrom, displayEmailFrom);
        }

        private static string GetSystemEmail()
        {
            return Convert.ToString(ConfigurationSettings.AppSettings["SystemEmail"]);

        }

        private static string GetSystemDisplayName()
        {
            return Convert.ToString(ConfigurationSettings.AppSettings["SystemDisplayName"]);

        }

        private static string GetSystemEmailPassWord()
        {
            return Convert.ToString(ConfigurationSettings.AppSettings["SystemMailPassword"]);

        }
    }

}
